//
//  PictureTakeView.m
//  AnotherMediaTool
//
//  Created by fh on 2018/9/10.
//  Copyright © 2018年 fh. All rights reserved.
//

#import "PictureTakeView.h"

@interface PictureTakeView () <UIGestureRecognizerDelegate>  {
    int _flashModeCycle;
}

/*** 记录开始的缩放比例 */
@property (nonatomic, assign) CGFloat beginGestureScale;
/*** 最后的缩放比例 */
@property (nonatomic, assign) CGFloat effectiveScale;

/** 预览图父视图 */
@property (nonatomic, strong) UIView *previewBackgroundView;
/** 返回按钮 */
@property (nonatomic, strong) UIButton *backButton;
/** 拍照按钮 */
@property (nonatomic, strong) CaptureButton *takePictureButton;
/** 前后摄像头切换按钮 */
@property (nonatomic, strong) UIButton *toggleButton;
/** 闪光灯按钮 */
@property (nonatomic, strong) UIButton *flashButton;
/** 聚焦光标 */
@property (nonatomic, strong) UIImageView *focusCursor;
/** 缩略图 */
@property (nonatomic, strong) UIImageView *thumbnail;

/** 变焦滑动条 */
//@property (nonatomic, strong) UISlider *slider;
/** 增加焦距按钮 */
//@property (nonatomic, strong) UIButton *zoomScaleAddButton;
/** 减小焦距按钮 */
//@property (nonatomic, strong) UIButton *zoomScaleSubButton;

/** 捏合事件回调: 暂时没用到，设置为私有 */
@property (nonatomic, copy) void(^pinchGestureRecognizerClickedBlock)(CGFloat scale);
/** 滑块事件回调 */
@property (nonatomic, copy) void(^sliderValueChangeClickBlock)(CGFloat value);

/** AVCaptureConnection方式变焦回调 */
@property (nonatomic, copy) void(^connectionZoomBlock)(CGFloat zoomScale);

@end

@implementation PictureTakeView

- (instancetype)init {
    if (self = [super init]) {
        
        _effectiveScale = 1.0;
        _beginGestureScale = 1.0; // 1
        
        _minScaleAndCropFactor = 1.0;
        _maxScaleAndCropFactor = 4.0;
        
        _flashModeCycle = 0;
        // 顶部比例0.06; 底部比例0.18
        self.backgroundColor = [UIColor blackColor];
        
        [self addSubview:self.previewBackgroundView];
        [self.previewBackgroundView addSubview:self.preview];
        [self addSubview:self.takePictureButton];
        [self addSubview:self.backButton];
        [self addSubview:self.toggleButton];
        [self addSubview:self.flashButton];
        [self.previewBackgroundView addSubview:self.focusCursor];
//        [self.previewBackgroundView addSubview:self.slider];
//        [self.previewBackgroundView addSubview:self.zoomScaleSubButton];
//        [self.previewBackgroundView addSubview:self.zoomScaleAddButton];
        
        [self.takePictureButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(@(-15));
            make.centerX.equalTo(self.mas_centerX);
            make.width.height.equalTo(@(70));
        }];
        
        [self.previewBackgroundView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(@(kkScreenHeight * 0.06));  // 22+30
            make.left.right.equalTo(@(0));
            //            make.bottom.equalTo(self.takePictureButton.mas_top).offset(-30);
            make.height.equalTo(@(kkScreenHeight*(1-0.06-0.18)));
        }];
        
        [self.preview mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.previewBackgroundView);
        }];
        
        [self.backButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.takePictureButton.mas_centerY);
            make.left.equalTo(@(20));
            make.width.height.equalTo(@(50));
        }];
        
        [self.toggleButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.takePictureButton.mas_centerY);
            make.right.equalTo(@(-20));
            make.width.height.equalTo(@(50));
        }];
        
        [self.flashButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@(20));
            make.top.equalTo(@(0)); // 22
//            make.height.equalTo(@(30));
//            make.width.equalTo(@(120));
            make.bottom.equalTo(self.preview.mas_top);
            make.width.equalTo(self.flashButton.mas_height);
        }];
        
        [self.focusCursor mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.height.width.equalTo(@(75));
            make.center.equalTo(self.previewBackgroundView);
        }];
        
//        [self.zoomScaleSubButton mas_remakeConstraints:^(MASConstraintMaker *make) {
//            make.left.equalTo(@(15));
//            make.bottom.equalTo(@(0));
//            make.width.height.equalTo(@(44));
//        }];
//
//        [self.zoomScaleAddButton mas_remakeConstraints:^(MASConstraintMaker *make) {
//            make.right.equalTo(@(-15));
//            make.bottom.equalTo(@(0));
//            make.width.height.equalTo(@(44));
//        }];
//
//        [self.slider mas_remakeConstraints:^(MASConstraintMaker *make) {
//            make.bottom.equalTo(self.previewBackgroundView.mas_bottom).offset(-5);
//            make.left.equalTo(self.zoomScaleSubButton.mas_right);
//            make.right.equalTo(self.zoomScaleAddButton.mas_left);
//        }];
        
    }
    return self;
}

#pragma mark - Event
- (void)takePictureButtonAction:(UIButton *)button {
    if(self.takePictureButtonClickedBlock) {
        self.takePictureButtonClickedBlock(button);
    }
}
- (void)backButtonAction:(UIButton *)button {
    if (self.backButtonClickedBlock) {
        self.backButtonClickedBlock(button);
    }
}
- (void)toggleButtonAction:(UIButton *)button {
    if (self.toggleButtonClickedBlock) {
        self.toggleButtonClickedBlock(button);
    }
}
- (void)flashButtonAction:(UIButton *)button {
   
    PictureTakeViewFlashMode mode = PictureTakeViewFlashModeOff;
    int value = (++_flashModeCycle)%3;
    switch (value) {
        case 0:
            [_flashButton setImage:[[UIImage imageNamed:@"camera_flash_off"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
            mode = PictureTakeViewFlashModeOff;
            break;
        case 1:
            [_flashButton setImage:[[UIImage imageNamed:@"camera_flash_on"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
            mode = PictureTakeViewFlashModeOn;
            break;
        case 2:
           [_flashButton setImage:[[UIImage imageNamed:@"camera_flash_auto"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
            mode = PictureTakeViewFlashModeAuto;
            break;
        default:
            break;
    }
    
    if (self.flashButtonClickedBlock) {
        self.flashButtonClickedBlock(button,mode);
    }
}

- (void)focusPreviewAction:(UITapGestureRecognizer *)tapGestureRecognizer {
    
    CGPoint point = [tapGestureRecognizer locationInView:self.previewBackgroundView];

//    self.focusCursor.bounds = CGRectMake(0, 0, 75, 75);
    self.focusCursor.center = point;
    self.focusCursor.transform = CGAffineTransformMakeScale(1.25, 1.25);
    self.focusCursor.alpha = 1.0;
    WeakSelf;
    [UIView animateWithDuration:0.6 animations:^{
        weakSelf.focusCursor.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
        weakSelf.focusCursor.alpha = 0;
    }];
    
    if (self.focusPreviewClickedBlock) {
        self.focusPreviewClickedBlock(tapGestureRecognizer,point);
    }
}

- (void)pinchGestureRecognizerAction:(UIPinchGestureRecognizer *)recognizer {
  
    BOOL allTouchesAreOnThePreviewLayer = YES;
    NSUInteger numTouches = [recognizer numberOfTouches], i;
    for ( i = 0; i < numTouches; ++i ) {
        CGPoint location = [recognizer locationOfTouch:i inView:self.preview];
        CGPoint convertedLocation = [self.preview.layer convertPoint:location fromLayer:self.preview.layer.superlayer];
        if ( ! [self.preview.layer containsPoint:convertedLocation] ) {
            allTouchesAreOnThePreviewLayer = NO;
            break;
        }
    }
    
    if (allTouchesAreOnThePreviewLayer) {
        self.effectiveScale = self.beginGestureScale * recognizer.scale;
    
        if (self.effectiveScale < self.minScaleAndCropFactor) {
            self.effectiveScale = self.minScaleAndCropFactor;
        }
        if (self.effectiveScale > self.maxScaleAndCropFactor) {
            self.effectiveScale = self.maxScaleAndCropFactor;
        }
        
//        [self scalePreViewWithScale:self.effectiveScale];
        
        CGFloat value = (self.effectiveScale - self.minScaleAndCropFactor)/(self.maxScaleAndCropFactor - self.minScaleAndCropFactor);
//        [self.slider setValue:value animated:YES];
       
//        if (self.connectionZoomBlock) {
//            self.connectionZoomBlock(self.effectiveScale);
//        }
        
        if (self.deviceZoomBlock) {
            self.deviceZoomBlock(value);
        }
    }
    
}

//- (void)zoomScaleAddButtonAction:(UIButton *)button {
//    CGFloat value = self.slider.value;
//    value += 0.1;
//    if (value > 1) {
//        value = 1;
//    }
//    [self.slider setValue:value animated:YES];
//    self.effectiveScale = value * (self.maxScaleAndCropFactor - self.minScaleAndCropFactor) + self.minScaleAndCropFactor;
//    if (self.anotherZoomBlock) {
//        self.anotherZoomBlock(value);
//    }
//}
//
//- (void)zoomScaleSubButtonAction:(UIButton *)button {
//    CGFloat value = self.slider.value;
//    value -= 0.1;
//    if (value < 0) {
//        value = 0;
//    }
//    [self.slider setValue:value animated:YES];
//    self.effectiveScale = value * (self.maxScaleAndCropFactor - self.minScaleAndCropFactor) + self.minScaleAndCropFactor;
//    if (self.anotherZoomBlock) {
//        self.anotherZoomBlock(value);
//    }
//}

- (void)sliderValueChangeAction:(UISlider *)sender {
    sender.alpha = 1;
    CGFloat value = sender.value * (self.maxScaleAndCropFactor - self.minScaleAndCropFactor) + self.minScaleAndCropFactor;
    if (value < self.minScaleAndCropFactor) {
        value = self.minScaleAndCropFactor;
    }
    if (value > self.maxScaleAndCropFactor) {
        value = self.maxScaleAndCropFactor;
    }
    
    self.effectiveScale = value * (self.maxScaleAndCropFactor - self.minScaleAndCropFactor) + self.minScaleAndCropFactor;
    //改变焦距
  //  [CATransaction begin];
  //  [CATransaction setAnimationDuration:0.2];
  //  [self.preview.layer setAffineTransform:CGAffineTransformMakeScale(value, value)];
  //  [CATransaction commit];
    
//    [UIView beginAnimations:nil context:nil];
//    [UIView setAnimationDuration:0.5];
//    [self.preview setTransform:CGAffineTransformMakeScale(value, value)];
//    [UIView commitAnimations];
    
//    [self scalePreViewWithScale:value];
    
//    if (self.connectionZoomBlock) {
//        self.connectionZoomBlock(value);
//    }
//    if (self.sliderValueChangeClickBlock) {
//        self.sliderValueChangeClickBlock(sender.value);
//    }
    if (self.deviceZoomBlock) {
        self.deviceZoomBlock(sender.value);
    }
}

// AVCaptureConnection方式改变焦距
- (void)scalePreViewWithScale:(CGFloat)scale {
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [self.preview setTransform:CGAffineTransformMakeScale(scale, scale)];
    [UIView commitAnimations];
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    if ( [gestureRecognizer isKindOfClass:[UIPinchGestureRecognizer class]] ) {
        self.beginGestureScale = self.effectiveScale;
    }
    return YES;
}


#pragma mark - Setter and getter
- (void)setMinScaleAndCropFactor:(CGFloat)minScaleAndCropFactor {
    _minScaleAndCropFactor = minScaleAndCropFactor;
    self.beginGestureScale = minScaleAndCropFactor;
    self.effectiveScale = minScaleAndCropFactor;
}

- (CaptureButton *)takePictureButton {
    if (!_takePictureButton) {
        _takePictureButton = [CaptureButton buttonWithType:UIButtonTypeCustom];
        _takePictureButton.isVideoCamera = NO;
        [_takePictureButton addTarget:self action:@selector(takePictureButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _takePictureButton;
}
- (UIView *)previewBackgroundView {
    if (!_previewBackgroundView) {
        _previewBackgroundView = [UIView new];
        _previewBackgroundView.clipsToBounds = YES;
        _previewBackgroundView.backgroundColor = UIColorFromHex(0xffb650);
        UITapGestureRecognizer *focusGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(focusPreviewAction:)];
        [_previewBackgroundView addGestureRecognizer:focusGesture];
    }
    return _previewBackgroundView;
}
- (UIView *)preview {
    if (!_preview) {
        _preview = [UIView new];
        _preview.backgroundColor = UIColorFromHex(0xff9a7a);
        UIPinchGestureRecognizer *pinTapGesture = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinchGestureRecognizerAction:)];
        pinTapGesture.delegate = self;
        [_preview addGestureRecognizer:pinTapGesture];
        
    }
    return _preview;
}
- (UIButton *)backButton {
    if (!_backButton) {
        _backButton = [UIButton new];
        [_backButton setImage:[[UIImage imageNamed:@"camera_cancle"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [_backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backButton;
}
- (UIButton *)toggleButton {
    if (!_toggleButton) {
        _toggleButton = [UIButton new];
        [_toggleButton setImage:[[UIImage imageNamed:@"camera_toggle"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [_toggleButton setImageEdgeInsets:UIEdgeInsetsMake(3, 3, 3, 3)];
        [_toggleButton addTarget:self action:@selector(toggleButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _toggleButton;
}
- (UIButton *)flashButton {
    if (!_flashButton) {
        _flashButton = [UIButton new];
        _flashButton.titleLabel.font = [UIFont systemFontOfSize:15];
        _flashButton.titleLabel.textAlignment = NSTextAlignmentLeft;
        [_flashButton addTarget:self action:@selector(flashButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_flashButton setImage:[[UIImage imageNamed:@"camera_flash_off"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [_flashButton setImageEdgeInsets:UIEdgeInsetsMake(8, 8, 8, 8)];
    }
    return _flashButton;
}
- (UIImageView *)focusCursor {
    if (!_focusCursor) {
        _focusCursor = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"camera_focus_orange"]];
        _focusCursor.alpha = 0;
    }
    return _focusCursor;
}

//- (UISlider *)slider {
//    if (!_slider) {
//        _slider = [[UISlider alloc] init];
//        _slider.thumbTintColor = [UIColor whiteColor];
//        _slider.minimumTrackTintColor = UIColorFromHex(0xffb650);
//        _slider.maximumTrackTintColor = [UIColor whiteColor]; // UIColorFromHex(0xff9a7a);
//        [_slider addTarget:self action:@selector(sliderValueChangeAction:) forControlEvents:UIControlEventValueChanged];
//    }
//    return _slider;
//}

//- (UIButton *)zoomScaleAddButton {
//    if (!_zoomScaleAddButton) {
//        _zoomScaleAddButton = [UIButton new];
//        _zoomScaleAddButton.titleLabel.font = [UIFont systemFontOfSize:20];
//        [_zoomScaleAddButton setTitle:@"+" forState:UIControlStateNormal];
//        [_zoomScaleAddButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//        [_zoomScaleAddButton addTarget:self action:@selector(zoomScaleAddButtonAction:) forControlEvents:UIControlEventTouchUpInside];
//    }
//    return _zoomScaleAddButton;
//}

//- (UIButton *)zoomScaleSubButton {
//    if (!_zoomScaleSubButton) {
//        _zoomScaleSubButton = [UIButton new];
//        _zoomScaleSubButton.titleLabel.font = [UIFont systemFontOfSize:20];
//        [_zoomScaleSubButton setTitle:@"-" forState:UIControlStateNormal];
//        [_zoomScaleSubButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//        [_zoomScaleSubButton addTarget:self action:@selector(zoomScaleSubButtonAction:) forControlEvents:UIControlEventTouchUpInside];
//    }
//    return _zoomScaleSubButton;
//}

@end
